#include<jsoncpp/json/json.h>
#include<iostream>
using namespace std;

void Serialize(){
  const char *name = "张三";
  int age = 18;
  float score[] = {88.5, 90, 56};

  Json::Value val;
  //存储的是K-V键值对
  val["姓名"] = name;
  val["年龄"] = age;
  val["成绩"].append(score[0]);
  val["成绩"].append(score[1]);
  val["成绩"].append(score[2]);

  Json::StyledWriter w;//格式化
  Json::FastWriter fw;//非格式化
  string str = w.write(val); 
  string fwstr = fw.write(val); 

  cout << str << endl;
  cout << fwstr << endl;

  //嵌套
  Json::Value root;
  root.append(val);
  cout << root << endl;

  
}

void UnSerialize(){
  //原始字符串示例---不必使用转移字符\来解决可能的冲突
  string str = R"("everyone:" : hello \n)";
  string str1 = R"("everyone:" : hello )))\n)";
  cout << str << endl;
  cout << str1 << endl;
  cout << endl << endl;
  
  string input = R"({"姓名":"张三","年龄":19,"成绩":[66, 32.3,99]})";
  cout << input << endl;

  Json::Value val;
  Json::Reader read;
  bool ret = read.parse(input, val);
  if(!ret){
    cout << "Json parse error" << endl;
    return ;
  }
  cout << val.toStyledString() << endl; 
  cout << val << endl << endl;

  cout << val["姓名"].asString() << endl;
  cout << val["年龄"].asInt() << endl;
  if(val["成绩"].isArray()){
    for(int i = 0; i < val["成绩"].size(); i++) 
      cout << val["成绩"][i].asFloat() << endl;
  }
  cout << endl << endl;
  for(auto& e:val["成绩"])
    cout << e << endl;
  cout << endl;
  cout << typeid(val["成绩"]).name() << endl;
  cout << typeid(val).name() << endl;
  cout << typeid(val["成绩"].asFloat()).name() << endl;
}


int main(){
 //Serialize();//序列化
  UnSerialize();//反序列化
  return 0;
}
